<template>
  <div class="task-detail-container">
    <!-- 任务状态和操作区域 -->
    <div class="task-status-section">
      <div class="status-badge" :class="`status-${task?.status}`">
        {{ getStatusText(task?.status || 0) }}
      </div>
      <div class="task-actions">
        <van-icon name="ellipsis" @click="showActionMenu = true" />
      </div>
    </div>

    <!-- 任务基本信息 -->
    <div class="task-info-card">
      <h1 class="task-title">{{ task?.task_title || '加载中...' }}</h1>
      
      <div class="task-meta">
        <div class="meta-item">
          <van-icon name="user-circle-o" size="14" />
          <span>创建者：{{ task?.creator?.username || '未知' }}</span>
        </div>
        <div class="meta-item">
          <van-icon name="clock-o" size="14" />
          <span>创建时间：{{ formatDate(task?.create_time) }}</span>
        </div>
        <div class="meta-item">
          <van-icon name="team" size="14" />
          <span>所属队伍：{{ task?.team?.name || '未分配队伍' }}</span>
        </div>
      </div>

      <div class="task-meta">
        <div class="meta-item">
          <van-icon name="calendar" size="14" />
          <span>截止日期：{{ formatDate(task?.deadline) || '无截止日期' }}</span>
        </div>
        <div class="priority-badge" :class="`priority-${task?.priority}`">
          {{ getPriorityText(task?.priority || 0) }}
        </div>
      </div>
    </div>

    <!-- 任务负责人 -->
    <div class="task-section">
      <div class="section-header">
        <span class="section-title">负责人</span>
        <div class="section-action" @click="handleAssign">
          <van-icon name="edit" size="14" />
          <span>分配</span>
        </div>
      </div>
      <div class="assignee-list" v-if="task?.assigneeList && task.assigneeList.length > 0">
        <div
          v-for="assignee in task.assigneeList"
          :key="assignee.id"
          class="assignee-item"
        >
          <div class="assignee-avatar">
            <img :src="assignee.avatarUrl || '/default-avatar.png'" alt="头像" />
          </div>
          <span class="assignee-name">{{ assignee.username }}</span>
        </div>
      </div>
      <div v-else class="empty-assignee">
        <span>暂无负责人</span>
      </div>
    </div>

    <!-- 任务描述 -->
    <div class="task-section">
      <div class="section-header">
        <span class="section-title">任务描述</span>
      </div>
      <div class="task-description">
        {{ task?.task_desc || '暂无描述' }}
      </div>
    </div>

    <!-- 任务进度 -->
    <div class="task-section">
      <div class="section-header">
        <span class="section-title">任务进度</span>
        <div class="section-action" v-if="isTaskAssignee || isTaskCreator" @click="showProgressModal = true">
          <van-icon name="edit" size="14" />
          <span>更新</span>
        </div>
      </div>
      <div class="progress-bar-container">
        <div class="progress-bar">
          <div 
            class="progress-fill" 
            :style="{ width: `${task?.progress || 0}%` }"
          ></div>
        </div>
        <span class="progress-text">{{ task?.progress || 0 }}%</span>
      </div>
    </div>

    <!-- 任务评论 -->
    <div class="task-section">
      <div class="section-header">
        <span class="section-title">评论 ({{ comments.length }})</span>
      </div>
      <div class="comment-list" v-if="comments.length > 0">
        <div v-for="comment in comments" :key="comment.id" class="comment-item">
          <div class="comment-avatar">
            <img :src="comment.user?.avatarUrl || '/default-avatar.png'" alt="头像" />
          </div>
          <div class="comment-content">
            <div class="comment-header">
              <span class="comment-author">{{ comment.user?.username || '匿名' }}</span>
              <span class="comment-time">{{ formatDateTime(comment.create_time) }}</span>
            </div>
            <div class="comment-text">{{ comment.content }}</div>
          </div>
        </div>
      </div>
      <div v-else class="empty-comments">
        <van-empty description="暂无评论" />
      </div>
    </div>

    <!-- 底部评论输入栏 -->
    <div class="bottom-comment-bar">
      <van-field
        v-model="commentText"
        placeholder="添加评论..."
        type="textarea"
        :rows="1"
        show-confirm-button
        confirm-text="发送"
        @confirm="handleSendComment"
      />
    </div>

    <!-- 操作菜单弹出层 -->
    <van-popup v-model:show="showActionMenu" position="bottom" round>
      <div class="action-menu">
        <div class="menu-item" @click="handleEdit">
          <van-icon name="edit" color="#1989fa" />
          <span>编辑任务</span>
        </div>
        <div class="menu-item" @click="handleDelete">
          <van-icon name="delete" color="#ee0a24" />
          <span>删除任务</span>
        </div>
        <div class="menu-item" @click="handleChangeStatus">
          <van-icon name="swap" color="#1989fa" />
          <span>更改状态</span>
        </div>
        <div class="menu-item menu-cancel" @click="showActionMenu = false">
          <span>取消</span>
        </div>
      </div>
    </van-popup>

    <!-- 进度更新弹窗 -->
    <van-popup v-model:show="showProgressModal" position="bottom" round>
      <div class="progress-modal">
        <div class="modal-header">
          <h3>更新任务进度</h3>
          <van-icon name="cross" @click="showProgressModal = false" />
        </div>
        <div class="progress-slider">
          <van-slider 
            v-model="progressValue" 
            :min="0" 
            :max="100" 
            :step="10"
            show-value
          />
        </div>
        <div class="modal-footer">
          <div class="cancel-btn" @click="showProgressModal = false">取消</div>
          <div class="confirm-btn" @click="handleUpdateProgress">确定</div>
        </div>
      </div>
    </van-popup>

    <!-- 状态更新弹窗 -->
    <van-popup v-model:show="showStatusModal" position="bottom" round>
      <div class="status-modal">
        <div class="modal-header">
          <h3>更改任务状态</h3>
          <van-icon name="cross" @click="showStatusModal = false" />
        </div>
        <div class="status-options">
          <div 
            v-for="option in statusOptions" 
            :key="option.value"
            :class="['status-option', { active: selectedStatus === option.value }]"
            @click="selectedStatus = option.value"
          >
            <div class="status-dot" :class="`status-${option.value}`"></div>
            <span>{{ option.label }}</span>
          </div>
        </div>
        <div class="modal-footer">
          <div class="cancel-btn" @click="showStatusModal = false">取消</div>
          <div class="confirm-btn" @click="handleConfirmStatus">确定</div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showToast, showDialog } from 'vant';
import { taskStore } from '../stores/task/task';
import { userStore } from '../stores/user/user';
import type { Task, TaskComment } from '../models/task';

const router = useRouter();
const route = useRoute();
const taskStoreAPI = taskStore();
const userStoreAPI = userStore();

// 状态管理
const taskId = computed(() => Number(route.params.id));
const task = ref<Task | null>(null);
const comments = ref<TaskComment[]>([]);
const showActionMenu = ref(false);
const showProgressModal = ref(false);
const showStatusModal = ref(false);
const progressValue = ref(0);
const selectedStatus = ref(0);
const commentText = ref('');

// 状态选项
const statusOptions = [
  { label: '待处理', value: 0 },
  { label: '进行中', value: 1 },
  { label: '已完成', value: 2 },
  { label: '已取消', value: 3 }
];

// 计算属性
const currentUser = computed(() => userStoreAPI.getCurrentUserInfo());

const isTaskCreator = computed(() => {
  return currentUser.value && task.value && 
    currentUser.value.id === task.value.creator?.id;
});

const isTaskAssignee = computed(() => {
  if (!currentUser.value || !task.value || !task.value.assigneeList) return false;
  return task.value.assigneeList.some((a: any) => a.id === currentUser.value?.id);
});

// 辅助函数
const getStatusText = (status: number) => {
  const map = { 0: '待处理', 1: '进行中', 2: '已完成', 3: '已取消' };
  return map[status as keyof typeof map] || '未知';
};

const getPriorityText = (priority: number) => {
  const map = { 1: '低', 2: '中', 3: '高' };
  return map[priority as keyof typeof map] || '未知';
};

const formatDate = (dateStr?: string) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

const formatDateTime = (dateStr?: string) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return `${date.getMonth() + 1}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 任务操作函数
const handleEdit = () => {
  showActionMenu.value = false;
  router.push(`/task/edit/${taskId.value}`);
};

const handleDelete = () => {
  showActionMenu.value = false;
  showDialog({
    title: '确认删除',
    message: '确定要删除这个任务吗？',
    confirmButtonText: '删除',
    confirmButtonColor: '#ee0a24',
  }).then(async () => {
    try {
      const res = await taskStoreAPI.deleteTask(taskId.value);
      if (res.code === 200) {
        showToast('删除成功');
        router.back();
      } else {
        showToast('删除失败');
      }
    } catch (error) {
      showToast('删除失败');
    }
  }).catch(() => {
    // 取消删除
  });
};

const handleChangeStatus = () => {
  showActionMenu.value = false;
  selectedStatus.value = task.value?.status || 0;
  showStatusModal.value = true;
};

const handleAssign = () => {
  router.push(`/task/assign/${taskId.value}`);
};

const handleUpdateProgress = async () => {
  try {
    const res = await taskStoreAPI.updateTaskProgress(taskId.value, progressValue.value);
    if (res.code === 200) {
      showToast('进度更新成功');
      showProgressModal.value = false;
      // 重新加载任务详情
      await loadTaskDetail();
    } else {
      showToast('进度更新失败');
    }
  } catch (error) {
    showToast('进度更新失败');
  }
};

const handleConfirmStatus = async () => {
  try {
    const res = await taskStoreAPI.updateTaskStatus(taskId.value, selectedStatus.value);
    if (res.code === 200) {
      showToast('状态更新成功');
      showStatusModal.value = false;
      // 重新加载任务详情
      await loadTaskDetail();
    } else {
      showToast('状态更新失败');
    }
  } catch (error) {
    showToast('状态更新失败');
  }
};

const handleSendComment = async () => {
  if (!commentText.value.trim()) {
    showToast('评论内容不能为空');
    return;
  }

  try {
    const res = await taskStoreAPI.addTaskComment(taskId.value, commentText.value);
    if (res.code === 200) {
      showToast('评论成功');
      commentText.value = '';
      // 重新加载评论列表
      await loadTaskComments();
    } else {
      showToast('评论失败');
    }
  } catch (error) {
    showToast('评论失败');
  }
};

// 数据加载函数
const loadTaskDetail = async () => {
  try {
    const res = await taskStoreAPI.fetchTaskDetail(taskId.value);
    if (res.code === 200) {
      task.value = res.data;
      progressValue.value = task.value.progress || 0;
    } else {
      showToast('获取任务详情失败');
      router.back();
    }
  } catch (error) {
    showToast('获取任务详情失败');
    router.back();
  }
};

const loadTaskComments = async () => {
  try {
    const res = await taskStoreAPI.fetchTaskComments(taskId.value);
    if (res.code === 200) {
      comments.value = res.data || [];
    }
  } catch (error) {
    console.error('获取评论失败:', error);
  }
};

// 初始化
onMounted(async () => {
  const user = await userStoreAPI.getCurrentUser();
  if (!user) {
    showToast('请先登录');
    router.push('/login');
    return;
  }
  await loadTaskDetail();
  await loadTaskComments();
});
</script>

<style scoped>
.task-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 70px; /* 为底部评论栏留出空间 */
}

.task-status-section {
  background-color: #fff;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1px;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
}

.status-0 {
  background-color: #f0f9ff;
  color: #1989fa;
}

.status-1 {
  background-color: #fff7e6;
  color: #faad14;
}

.status-2 {
  background-color: #f6ffed;
  color: #52c41a;
}

.status-3 {
  background-color: #f5f5f5;
  color: #999;
}

.task-actions .van-icon {
  font-size: 20px;
  color: #666;
}

.task-info-card {
  background-color: #fff;
  padding: 16px;
  margin-bottom: 10px;
}

.task-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.task-meta {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 8px;
}

.meta-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;
}

.meta-item .van-icon {
  margin-right: 4px;
}

.priority-badge {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.priority-1 {
  background-color: #f0f9ff;
  color: #1989fa;
}

.priority-2 {
  background-color: #fff7e6;
  color: #faad14;
}

.priority-3 {
  background-color: #fff1f0;
  color: #f5222d;
}

.task-section {
  background-color: #fff;
  margin-bottom: 10px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f5f5f5;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.section-action {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #1989fa;
}

.section-action .van-icon {
  margin-right: 4px;
}

.assignee-section,
.task-description,
.task-verify,
.parent-task,
.subtasks,
.comments-section {
  margin-top: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.assignee-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.assignee-item {
  display: flex;
  align-items: center;
}

.assignee-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 8px;
}

.assignee-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.assignee-name {
  font-size: 14px;
  color: #666;
}

.empty-assignee {
  padding: 20px 16px;
  color: #999;
  font-size: 14px;
}

.task-description {
  padding: 16px;
  font-size: 14px;
  line-height: 1.6;
  color: #666;
  white-space: pre-wrap;
}

.progress-bar-container {
  padding: 16px;
  display: flex;
  align-items: center;
}

.progress-bar {
  flex: 1;
  height: 8px;
  background-color: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 12px;
}

.progress-fill {
  height: 100%;
  background-color: #1989fa;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 14px;
  font-weight: 500;
  color: #1989fa;
}

.comment-list {
  max-height: 300px;
  overflow-y: auto;
}

.comment-item {
  display: flex;
  padding: 16px;
  border-bottom: 1px solid #f5f5f5;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 12px;
}

.comment-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
}

.comment-author {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-text {
  font-size: 14px;
  line-height: 1.5;
  color: #666;
}

.empty-comments {
  padding: 40px 0;
}

.bottom-comment-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 10px 16px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  border-top: 1px solid #eee;
}

/* 弹窗样式 */
.action-menu {
  padding: 16px;
}

.menu-item {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 12px;
  background-color: #f5f5f5;
}

.menu-item .van-icon {
  margin-right: 10px;
  font-size: 20px;
}

.menu-cancel {
  background-color: #fff;
  border: 1px solid #eee;
  color: #666;
}

.progress-modal,
.status-modal {
  padding: 20px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.modal-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.modal-header .van-icon {
  font-size: 20px;
  color: #999;
}

.progress-slider {
  margin-bottom: 30px;
}

.status-options {
  margin-bottom: 30px;
}

.status-option {
  display: flex;
  align-items: center;
  padding: 12px;
  margin-bottom: 10px;
  border-radius: 8px;
}

.status-option.active {
  background-color: #f0f9ff;
}

.status-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 12px;
}

.modal-footer {
  display: flex;
  gap: 12px;
}

.cancel-btn,
.confirm-btn {
  flex: 1;
  padding: 12px;
  text-align: center;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background-color: #1989fa;
  color: #fff;
}
</style>